package com.platform.qujia.utils.weixinapp;


import com.alibaba.fastjson.JSON;
import com.platform.qujia.utils.HttpClientUtil;
import com.platform.qujia.utils.StringUtils;
import com.platform.qujia.utils.exception.EndingException;
import com.platform.qujia.utils.redis.RedisCacheUtil;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <Title>工具类: WeiXinUtil</Title>
 * <description> 获取微信用户信息和凭证 </description>
 * @author JK
 * @date 2019年11月10日
 */
@Component
public class WeiXinUserUtil {

    @Resource
    private RedisCacheUtil redisCacheUtil;

    //微信小程序获取用户信息 https://api.weixin.qq.com/sns/userinfo
    //public final static String weiXinUserInfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
    //凭证获取路径
    public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    //微信小程序路径获取openID "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=CODE&grant_type=authorization_code";
    public final static String OPENID_URL  ="https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=CODE&grant_type=authorization_code";

    //微信公众号获取通过code换取网页授权access_token
    public final static String GZHAUTHORIZEINFO_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    //微信公众号获取通过code换取网页授权access_token  第三方拉取用户信息
    public final static String GZHAUTHORIZEINFO_disanfang_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9c0405ce1a9d3723&redirect_uri=https://yftx-test.xailife.com/login&response_type=code&scope=snsapi_base&state=0&component_appid=wx1a6ffff28789b899#wechat_redirect";

    //获取UnionId
    public final static String unionId_Url ="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    //获取公众号jsapi_ticket
    private static final String JSAPI_TICKET_URL ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

    //获取公众号微信卡api_ticket ticket/getticket
    private static final String CARD_API_TICKET_URL ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card";

    //客服系统退给用户消息 CUSTOMER_DIALOGUE
    private static final String CUSTOMER_DIALOGUE_RUL ="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";

    //获取用户AccessToken
    private static final String USER_ACCESS_TOKEN ="https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=APPID&code=CODE&grant_type=authorization_code&component_appid=wx61be193e633e76cf&component_access_token=COMPONENT_ACCESS_TOKEN";
    //日志
    private static final Logger logger = LoggerFactory.getLogger(WeiXinUserUtil.class);

//    @Value("${domain.adminName}")
    private static String adminName;


    @Value("${domain.adminName}")
    public void setName(String adminName) {
        WeiXinUserUtil.adminName = adminName;
    }



    /**
     * 获取用户AccessToken
     * @param
     * @return
     */
    public static JSONObject getUserAccessToken(String appId,String code){

        String requestUrl =USER_ACCESS_TOKEN.replace("APPID",appId).replace("CODE",code).replace("COMPONENT_ACCESS_TOKEN",ThirdPartyWeChatAccessToken());
        logger.info(requestUrl+"----------------");
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取用户公众号的授权后信息第三方" + jsonObject.toString());

        return jsonObject;
    }

    /**
     * 获取第三token
     * @param
     * @return
     */
    private static String ThirdPartyWeChatAccessToken(){
        try {
            RestTemplate restTemplate = new RestTemplate();
            String token=restTemplate.getForObject(adminName + "/prod-api/thirdParty/weChat/getAccessToken",String.class);
//            JSONObject  jsonObject = HttpRequestUtil.getHttpsRequestData(adminName + "/prod-api/thirdParty/weChat/getAccessToken", "GET", null);
            return token;
        }catch (Exception e){
            logger.info(e.toString());
        }
        return null;
    }



    /*
     * 获取公众号微信卡券api_ticket
     * @param accessToken
     * @return
     */
    public static JSONObject getGzhCardApiTicket(String accessToken){
        String requestUrl =CARD_API_TICKET_URL.replace("ACCESS_TOKEN",accessToken);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取公众号微信卡券api_ticket：" + jsonObject.toString());
        return jsonObject;

    }

    /*
     * 获取公众号jsapi_ticket
     * @param accessToken
     * @return
     */
    public static JSONObject getGzhJsapiTicket(String accessToken){
        String requestUrl =JSAPI_TICKET_URL.replace("ACCESS_TOKEN",accessToken);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取公众号jsapi_ticket：" + jsonObject.toString());
        return jsonObject;

    }


    /*
     * 获取用户公众号的授权信息
     * @param appId
     * @param appSecret
     * @param code
     * @return
     */
    public static JSONObject getGzhUserInfo(String appId, String appSecret, String code){
        logger.info("appId参数: "+ appId+" ;appSecret参数: " +appSecret +" ;code参数: " +code);
        String requestUrl = GZHAUTHORIZEINFO_disanfang_URL;
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取用户公众号的授权后信息：" + jsonObject.toString());
        return jsonObject;
    }

    /*
     * 获取用户公众号的授权信息
     * @param appId
     * @param appSecret
     * @param code
     * @return
     */
    public static JSONObject getGzhAuthorizeInfo(String appId, String appSecret, String code){
        logger.info("appId参数: "+ appId+" ;appSecret参数: " +appSecret +" ;code参数: " +code);
        String requestUrl = GZHAUTHORIZEINFO_URL.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取用户公众号的授权后信息：" + jsonObject.toString());
        return jsonObject;
    }

    /*
     * 获取公众号UnionId信息
     * @param accessToken
     * @param openId
     * @return
     */
    public static JSONObject getUnionIdInfo(String accessToken, String openId){
        String requestUrl = unionId_Url.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("获取UnionId信息：" + jsonObject.toString());
        return jsonObject;
    }

    /*
     * 获取用户的openid和session_key 格式例子:{"session_key":"rlxKT/xhq2bxAuvrMeEq8Q==","openid":"o9RM50ppeCgx065T2PvJjtzB_Gmo"}
     * @param appId     //凭证
     * @param appSecret     //密钥
     * @param code
     * @return
     */
    public static Map<String, Object> getUserSessionKeyAndOpenID(String appId, String appSecret, String code){
        String requestUrl = OPENID_URL.replace("APPID", appId).replace("APPSECRET", appSecret).replace("CODE", code);
        Map<String, Object> resultMap = new HashMap<>();
        //发起GET请求
        JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
        logger.info("/loginGetPhone:getUserSessionKeyAndOpenID--返回值:" + jsonObject.toString());

        if(jsonObject != null && jsonObject.containsKey("openid")){
            resultMap.put("openId", jsonObject.getString("openid"));
        }
        if(jsonObject != null && jsonObject.containsKey("session_key")){
            resultMap.put("sessionKey", jsonObject.getString("session_key"));
        }
        if(jsonObject != null && jsonObject.containsKey("unionid")){
            resultMap.put("unionId", jsonObject.getString("unionid"));
        }
        resultMap.put("code", code);
        resultMap.put("appid", appId);

        return resultMap;
    }


    /*
     * 获取接口访问凭证
     * 发请求的 以后少用 直接用getAccessToken就行
     * @param appId         //凭证
     * @param appSecret     //密钥
     * @return
     */
    public static Token getToken(String appId, String appSecret){
        Token token = null;
        if (Objects.isNull(appSecret)){
            token = new Token();
            RestTemplate restTemplate = new RestTemplate();
            String to=restTemplate.getForObject(adminName + "/prod-api/thirdParty/weChat/getAccessToken?authorizerAppid="+appId,String.class);
            token.setAccessToken(to);
            token.setExpiresIn(7200);
        }else {
            String requestUrl = token_url.replace("APPID", appId).replace("APPSECRET", appSecret);
            //发起GET请求获取凭证
            JSONObject jsonObject = HttpRequestUtil.getHttpsRequestData(requestUrl, "GET", null);
            logger.info(appId + "getToken: " + jsonObject);
            if (jsonObject != null) {
                try {
                    token = new Token();
                    token.setAccessToken(jsonObject.getString("access_token"));
                    token.setExpiresIn(jsonObject.getInt("expires_in"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return token;
    }


//    public synchronized String getAccessToken(String appId, String appSecret){
//        //redis缓存key
//        String accessTokenKey = "access_token_" + appId;
//        if(!redisCacheUtil.hasKey(accessTokenKey) || StringUtils.isBlank(redisCacheUtil.getCacheObject(accessTokenKey))){
//            String token = this.getToken(appId, appSecret).getAccessToken();
//            redisCacheUtil.setCacheObject(accessTokenKey, token);
//            redisCacheUtil.expire(accessTokenKey, 7100, TimeUnit.SECONDS);
//            logger.info("getTokenByRedisCache-set appId "+ appId + " 's token is " + token);
//            return token;
//        }else {
//            String token = redisCacheUtil.getCacheObject(accessTokenKey);
//            logger.info("getTokenByRedisCache-get appId "+ appId + " 's token is " + token);
//            return token;
//        }
//    }


    /*
     * 客服对话框推送消息
     * @param accessToken
     * @return
     */
//    public  void customerDialogue(String openId, String text, String type) throws EndingException {
//        try {
//
//
//            String accessToken = this.getAccessToken("", "1");
//            String requestUrl = CUSTOMER_DIALOGUE_RUL.replace("ACCESS_TOKEN", accessToken);
//            HashMap<String, Object> paramsHashMap = new HashMap<>();
//            paramsHashMap.put("touser", openId);
//
//
//            if ("text".equals(type)) {
//                HashMap<String, Object> textHashMap = new HashMap<>();
//                textHashMap.put("content", "--------");
//
//                paramsHashMap.put("msgtype", "text");
//                paramsHashMap.put("text", textHashMap);
//            } else if ("image".equals(type)) {
//                HashMap<String, Object> imageHashMap = new HashMap<>();
//                imageHashMap.put("media_id", "---------");
//
//                paramsHashMap.put("msgtype", "image");
//                paramsHashMap.put("image", imageHashMap);
//            } else if ("link".equals(type)) {
//                HashMap<String, Object> linkHashMap = new HashMap<>();
//                linkHashMap.put("title", "-----------");
//                linkHashMap.put("description", "----------");
//                linkHashMap.put("url", "-----------");
//                linkHashMap.put("thumb_url", "thumb_url");
//
//                paramsHashMap.put("msgtype", "link");
//                paramsHashMap.put("link", linkHashMap);
//            } else if ("miniprogrampage".equals(type)) {
//                HashMap<String, Object> miniHashMap = new HashMap<>();
//                miniHashMap.put("title", "-----------");
//                miniHashMap.put("pagepath", "");
//                miniHashMap.put("thumb_media_id", "-----------");
//
//                paramsHashMap.put("msgtype", "miniprogrampage");
//                paramsHashMap.put("miniprogrampage", miniHashMap);
//            } else {
//                throw new EndingException("type类型不对");
//            }
//
//            JSONObject resultJson = HttpClientUtil.doPostJson(requestUrl, JSON.toJSONString(paramsHashMap));
//
//            logger.info("resultJson：" + resultJson);
//            logger.info("resultJson：" + resultJson.get("errcode"));
//            logger.info("resultJson：" + resultJson.get("errmsg"));
//        } catch (EndingException e) {
//            logger.info("customerDialogue-", e.getMessage());
//        } catch (Exception e){
//            logger.info("customerDialogue-", e);
//        }
//    }
}
